import Vue from 'vue'
import VueRouter from 'vue-router'
import configRouter from '@/router.config'
import { Notification } from 'element-ui'
import ax from '@/api/_axios-config'
import * as apis from '@/api/_api'

Vue.use(VueRouter)

const router = new VueRouter({
  history: true,
  saveScrollPosition: true,
  routes: configRouter
})

router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth && to.name !== 'login') {
    if (window.localStorage.getItem('token') != null || window.localStorage.getItem('admin') != null) {
      // 判断登录状态
      ax.get(apis.PROBE).then(
        response => {
          next()
        }
      ).catch(
        err => {
          Notification({
            title: '异常',
            type: 'error',
            message: err.toString(),
            duration: 3000
          })
        }
      )
    } else {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    }
  } else {
    next()
  }
})

export default router
